package gripper.ftp.handle;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import gripper.ftp.FtpSession;
import gripper.ftp.PathConvert;

public class MKDHandle implements Handle {
	FtpSession ftpSession;

	public MKDHandle(FtpSession ftpSession) {
		this.ftpSession = ftpSession;
	}

	public void process(String line, BufferedReader br, OutputStream os) throws IOException {
		String dir=line.substring(line.indexOf(' '));
		dir=dir.trim();
		if(dir==null||dir.trim().length()<=0){
			os.write(("550 Requested action not taken.\r\n").getBytes());
			os.flush();
			return;
		}
		/**
		 * if not absolute path 
		 */
		if(!(dir.charAt(0)=='/')){
			dir=ftpSession.currentDir+"/"+dir.trim();
		}
		String path = PathConvert.toServerPath(ftpSession.getRootDir(), dir);
		Path p=Paths.get(path);
		Files.createDirectory(p);
		os.write(("257 \""+dir+"\" directory created").getBytes());
		os.flush();
	}
}
